import java.util.concurrent.CountDownLatch;

/**
 * author: MaHX
 * date: 2019/9/17/21:55
 * description: 闭锁，在其他线程执行完之后才执行当前线程的方法
 **/
public class TestCountDownLatch {
    public static void main(String args[]) {
        final CountDownLatch countDownLatch = new CountDownLatch(5);
        CountDownLatchDemo countDownLatchDemo = new CountDownLatchDemo(countDownLatch);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5; i++) {
            new Thread(countDownLatchDemo).start();
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("消耗时间为：" + (end - start));
    }


    static class CountDownLatchDemo implements Runnable {
        private CountDownLatch countDownLatch;

        public CountDownLatchDemo(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            synchronized (this) {
                for (int i = 0; i < 50; i++) {
                    if (i % 2 == 0) {
                        System.out.println(i);
                    }
                }
                countDownLatch.countDown();
            }
        }
    }
}

